from django.shortcuts import render, HttpResponse
from Comics.models import Comic
from BaseHtml.tool.Catalog import readCatalog, createCatalog, read_or_greate
from BaseHtml.tool import zip
from django.conf import settings
import os


# Create your views here.
def desktop(request):
    return render(request, "Comics/desktop.html")
    pass


def comics_house(request):
    com_list = Comic.objects.filter(isShow=True)

    return render(request, "Comics/comics_house.html", {"comics": com_list})
    pass


def upload(request):
    return render(request, "Comics/Upload.html")


def show_comics(request, comics_id):
    comic = Comic.objects.get(id=str(comics_id))
    if comic.isShow is True:
        comics_catalog = None
        p = None
        path = str(comic.comic_url).replace('.zip', "")
        path = os.path.join(settings.MEDIA_ROOT, str(comic.comic_url).replace(".zip", ""))
        try:
            comics_catalog, p = readCatalog(path=(path + ".json"))
        except FileNotFoundError:
            createCatalog(path)
            comics_catalog, p = readCatalog(path + ".json")
        context = {
            "comics_name": comic.name,
            "comics_summary": comic.introduction,
            "comics_catalog": comics_catalog,
            "comics_id": comics_id,
            "comic_cover": comic.cover,
        }
        return render(request, "Comics/show_comics.html", context)
    return HttpResponse("漫画不展示")


def comics(request, comics_id, catalog):
    comic = Comic.objects.get(id=str(comics_id))
    comics_catalog = None
    p = None
    next = None
    last = None
    if comic.isShow is True:
        # -------------读取章节-----------------
        p = None
        path = os.path.join(settings.MEDIA_ROOT, str(comic.comic_url).replace(".zip", ""))
        comics_catalog, p = read_or_greate(path + ".json")
        # ------------------------------------------------------
        comics_src = []
        # -----------章节内每个p的url生成-------------------
        for url in p[catalog]:
            comics_src.append(os.path.join(str(comic.comic_url).replace(".zip", ""), catalog, url).replace("\\", "/"))
        # ---------------------上一章and下一章----------------------------
        if comics_catalog.index(catalog) - 1 >= 0:
            last = comics_catalog[comics_catalog.index(catalog) - 1]
        if comics_catalog.index(catalog) + 1 < len(comics_catalog):
            next = comics_catalog[comics_catalog.index(catalog) + 1]
        # ------------------------------------------------------
        print("test" + comics_id)
        context = {
            "comics_id": comics_id,
            "comics_name": comic.name,
            "comics_src": comics_src,
            "next": next,
            "last": last,
        }
        return render(request, "Comics/comics.html", context)
    else:
        return HttpResponse("Not fond")


def create_comic(request):
    if request.method == "POST":
        name = request.POST["comic_name"]
        author = request.POST["author_name"]
        cover = request.FILES.get("comic_cover")
        comic_url = request.FILES.get("comic_zip")
        introduction = request.POST["introduction"]
        if name is not None and comic_url is not None and cover is not None:
            comic = Comic(
                name=name,
                author=author,
                cover=cover,
                comic_url=comic_url,
                introduction=introduction,
            )
            comic.save()
        print(comic.comic_url)
        zip.upzip(filePath=os.path.join(settings.MEDIA_ROOT, str(comic.comic_url)))
        createCatalog(path=os.path.join(settings.MEDIA_ROOT, str(comic.comic_url).replace(".zip", "")))
        return HttpResponse("succeed")
    return render(request, "Comics/create_comic.html")


def my_comics(request):
    comics = []
    for comic in Comic.objects.all():
        comics.append(
            {
                "id": comic.id,
                "name": comic.name,
                "cover": comic.cover,
                "showStatus": comic.isShow,
            }
        )
    return render(request, "Comics/my_comics.html", {"comics": comics})


def comics_manager(request):
    if request.method == "POST":
        id = request.POST['id']
        isShow = request.POST["isShow"]
        comic = Comic.objects.get(id=id)
        print(isShow)
        comic.isShow = isShow
        comic.save()
        return HttpResponse("succeed!\nid:" + id + "\nisShow:" + isShow)
    return 0
